package com.rxw.nutmall.oss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.rxw.nutmall.oss.entity.File;
import com.rxw.nutmall.oss.mapper.FileMapper;
import com.rxw.nutmall.oss.service.FileService;
import com.rxw.nutmall.oss.utils.MinioUtil;
import com.rxw.nutmall.service.impl.BaseServiceImpl;
import com.rxw.nutmall.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;

@Service
public class FileServiceImpl extends BaseServiceImpl<FileMapper, File> implements FileService {
    @Override
    public Result<File> getObject(File file) {
        LambdaQueryWrapper<File> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(file.getFileName()),File::getFileName, file.getFileName());
        File result = baseDao.selectOne(queryWrapper);
        return Result.ok(result);
    }

    @Override
    public Result<String> uploadFile(MultipartFile multipartFile, String folder) {
        Long count;
        String fileName = multipartFile.getOriginalFilename();
        if (StringUtils.isNotBlank(folder)) {
            fileName = folder + "/" +fileName;
        }
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file_name", fileName);
        count = baseDao.selectCount(queryWrapper);
        File uploaded = MinioUtil.upload(multipartFile, folder);
        if (uploaded != null) {
            if (count > 0) {
                File updateVO = new File();
                updateVO.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                baseDao.update(updateVO,new UpdateWrapper<File>().eq("file_name", uploaded.getFileName()));
            } else {
                baseDao.insert(uploaded);
            }
            return Result.success("上传成功");
        }
        return Result.error("上传失败");
    }

    @Override
    public String getFileUrl(File file) {
        return MinioUtil.getFileUrl(file.getFileName());
    }
}
